package com.centling.smartSealForPhone.fragment;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.telephony.TelephonyManager;

import com.centling.smartSealForPhone.utils.OkHttpUtil;
import com.wsdk.view.ProcessDialog;

import java.util.Map;
import java.util.Random;

/**
 * @author fionera
 */
public class BaseFragment
        extends Fragment {

    protected ProcessDialog mProcessDialog;
    protected Context mContext;
    protected Activity mActivity;
    private String globalCode = "";

    @SuppressLint({"HardwareIds"})
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        TelephonyManager telephonyManager = (TelephonyManager) mContext.getSystemService(Context
                .TELEPHONY_SERVICE);
        if (ActivityCompat.checkSelfPermission(mContext,
                Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        String imei = telephonyManager.getDeviceId();
        if (imei == null) {
            imei = new Random().toString();
        }
        globalCode = imei + System.currentTimeMillis();
    }

    @Override
    public void onAttach(Context context) {
        setHasOptionsMenu(true);
        mContext = context;
        mActivity = (Activity) context;
        mProcessDialog = new ProcessDialog(mContext);
        super.onAttach(context);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        OkHttpUtil.cancelCallWithTag("OkHttpCall_" + this.hashCode());
    }

    protected void getEnqueue(String url, OkHttpUtil.NetCallBack responseCallback) {
        OkHttpUtil.getEnqueue(url, responseCallback, "OkHttpCall_" + this.hashCode());
    }

    protected void postJsonEnqueue(String url, Map<String, String> params,
                                   OkHttpUtil.NetCallBack responseCallback) {
        OkHttpUtil.postJsonEnqueue(url.contains(
                "?") ? url + "&reqIdentifer=" + globalCode : url + "?reqIdentifer=" + globalCode,
                params, responseCallback, "OkHttpCall_" + this.hashCode());
    }

    protected void putJsonEnqueue(String url, Map<String, String> params,
                                  OkHttpUtil.NetCallBack responseCallback) {
        OkHttpUtil.putJsonEnqueue(url, params, responseCallback, "OkHttpCall_" + this.hashCode());
    }
}
